package com.auoem.radio.ui.msg;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.auoem.radio.R;
import com.auoem.radio.base.BaseFragment;
import com.auoem.radio.common.adapter.BindingAdapter;
import com.auoem.radio.common.custview.MsgDialogFragment;
import com.auoem.radio.common.custview.wheel.SimplePickerDialog;
import com.auoem.radio.databinding.FragmentMsgBinding;
import com.auctus.am.framework.constants.AmConstants;
import com.auctus.am.framework.entity.Contact;
import com.auctus.am.framework.imp.HlThreadPoolManager;
import com.auctus.am.framework.imp.MsgControl;
import com.auctus.am.framework.imp.RadioManager;
import com.auctus.am.framework.interfaces.ComCallback;
import com.auctus.am.framework.picker.IIntPickDataWrap;
import com.auctus.am.framework.roomdb.entity.AmMsg;
import com.auctus.am.framework.roomdb.entity.AmTalk;
import com.auctus.am.framework.utils.LogM;

import java.util.ArrayList;
import java.util.List;
import java.util.function.IntConsumer;

public class MsgFragment extends BaseFragment implements View.OnClickListener, MsgControl.MsgListener, IntConsumer {

    private static final String TAG = "MsgFragment";
    private FragmentMsgBinding mBinding;

    private List<AmMsg> msgList;
    private BindingAdapter<AmMsg> msgAdapter;

    private IIntPickDataWrap pickDataCt;
    private SimplePickerDialog mSelectDialog;

    private MsgControl msgControl;
    private MsgDialogFragment msgDialog;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        mBinding = FragmentMsgBinding.inflate(inflater);
        initData();
        return mBinding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        msgControl.setMsgListener(this);
        requestAndUpdateMsgList();
    }

    @Override
    public void onPause() {
        msgControl.setMsgListener(null);
        super.onPause();
    }

    private void initData() {
        msgControl = RadioManager.getInstance().getMsgControl();
//        msgControl.setMsgListener(this);
        msgList = new ArrayList<>();
        msgAdapter = new BindingAdapter<>(getActivity(), msgList, R.layout.adapter_item_mms);
        msgAdapter.setOnItemClickListener(this);
        mBinding.lvMsg.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.lvMsg.setAdapter(msgAdapter);
        LogM.d("ChFragment", "initData: " + msgList.size());
        pickDataCt = RadioManager.getInstance().getRadioData().getCtPicker();
    }


    @Override
    public void onClick(View v) {
        if (v == mBinding.btSend) {
            selCtSend();
        }
    }

//    private void doSendMsg(int tarId, String name) {
//        String content = mBinding.etContact.getText().toString().trim();
//        msgControl.sendMsg(tarId, name, content, new ComCallback() {
//            @Override
//            public void onCallback(Object o, int code, String inf) {
//                if (code == CODE_SUCCESS) {
//                    requestAndUpdateMsgList();
//                } else {
//                    toastResultUI(inf);
//                }
//            }
//        });
//    }

    private void doSendMsgOnCt(Contact contact) {
        showProgress(R.string.hl_msg_sending);
        String content = mBinding.etContact.getText().toString().trim();
        msgControl.sendMsg(contact, content, new ComCallback() {
            @Override
            public void onCallback(Object o, int code, String inf) {
                if (code == CODE_SUCCESS) {
                    requestAndUpdateMsgList();
                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            cancelProgress();
                            mBinding.etContact.setText("");
                        }
                    });
                } else {
                    toastResultUI(inf);
                }
            }
        });
    }


    @Override
    public void onNewMsg(AmTalk talk, AmMsg msg) {
        LogM.d(TAG, "onNewMsg: " + talk.toString());
        requestAndUpdateMsgList();
    }

    private void requestAndUpdateMsgList() {
        if (AmConstants.IS_MSG_ALL) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    msgList.clear();
                    msgList.addAll(msgControl.getMsgListBuffer());
                    if (msgList.size() >= 1) {
                        LogM.d(TAG, "requestAndUpdateMsgList ,index 0: " + msgList.get(0).toString());
                    }
                    msgAdapter.notifyDataSetChanged();
                }
            });
        } else {
            HlThreadPoolManager.getInstance().execut("requestTalkDb", new Runnable() {
                @Override
                public void run() {
                    List<AmMsg> newMsgs = msgControl.getMsgs();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //todo  update titlebar
                            msgList.clear();
                            msgList.addAll(newMsgs);
                            msgAdapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        }
    }

    private void selCtSend() {
        showSingleSelect(pickDataCt, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                Contact contact = RadioManager.getInstance().getRadioData().getContactOnTag(v1);
//                String name = pickDataCt.getDisp(sel1);
                doSendMsgOnCt(contact);
            }
        });
    }

    public void showSingleSelect(IIntPickDataWrap intPickDataWrap, SimplePickerDialog.OnPickListener onPickListener) {
        if (mSelectDialog == null) {
            mSelectDialog = new SimplePickerDialog(getActivity(), intPickDataWrap, 0, onPickListener, null);
        } else {
            mSelectDialog.update(intPickDataWrap, SimplePickerDialog.INVALID, onPickListener, null);
        }
        mSelectDialog.show();
    }

    private void showMsg(int position) {
        AmMsg amMsg = msgList.get(position);
        if (msgDialog == null) {
            msgDialog = new MsgDialogFragment(amMsg);
        } else {
            msgDialog.setMsg(amMsg);
        }
        if (!msgDialog.isAdded() && null == requireActivity().getSupportFragmentManager().findFragmentByTag("msgDialog")) {
            msgDialog.showNow(requireActivity().getSupportFragmentManager(), "msgDialog");
        }

    }

    @Override
    public void accept(int value) {
        showMsg(value);
    }
}
